package io.xmu.dataanalysis.data.dynamic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.annotation.PostConstruct;

import io.xmu.dataanalysis.data.BaseDataCache;
import io.xmu.dataanalysis.entity.Goods;
import io.xmu.dataanalysis.entity.Search;
import io.xmu.dataanalysis.repository.SearchRepo;
import io.xmu.dataanalysis.util.RandomUtils;

/**
 * @author lepdou 2017-02-27
 */
@Component
public class SearchMocker implements Mocker {

  Random random = new Random();

  @Autowired
  private BaseDataCache dataCache;
  @Autowired
  private SearchRepo searchRepo;

  @Autowired
  private Environment environment;
  private Map<String, Integer> wordMapCate = new HashMap<>();
  private Object[] words;
  private boolean hasInited = false;

  public void init() {

    String data = environment.getProperty("search");
    String[] groupData = data.split("#");
    for (String g: groupData) {
      String[] m = g.split("@");
      String cate = m[0];
      Integer cateId = dataCache.cateId(cate);
      if (cateId == null) {
        continue;
      }

      String[] words = m[1].split(",");
      for (String word: words) {
        wordMapCate.put(word, cateId);
      }
    }

    words =  wordMapCate.keySet().toArray();

  }

  public void mock(String dateToDay, int size) {
    if (!hasInited) {
      init();
      hasInited = true;
    }

    List<Search> searches = new LinkedList<>();

    for (int i = 0; i < size; i++) {
      Search search = new Search();

      String word = randomWord().toString();
      search.setKey(word);
      search.setCateId(wordMapCate.get(word));
      search.setSearchTime(RandomUtils.randomDate(dateToDay));

      searches.add(search);
    }

    searchRepo.save(searches);
  }

  private Object randomWord() {
    return words[random.nextInt(words.length)];
  }
}
